%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% O-Ring Production Networks
%   Author: Demir, Fieler, Xu, Yang
%   Last updated: December 2020
%
% Purpose: Estimation (Full Model)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all; diary off; clc; clear; 
global num_guess


%% Parameter, Data moments, and Initial values
    
    % parameters
    define_param
    
    % data moment
    define_data_moment
    
    % initial values
    init = [8.3679e-04, ...     % *1. matching friction (kappa)
            2.7811, ...         % *2. sd of directed search (nu_v)
            0.4298, ...         % 3. complementarity (nu_y)
            -3.7497, ...        % 4. mean of log export cost (mu_E)
            1.5449, ...         % *5. sd of log export cost (sigma_E)
            105.0402, ...       % 6. foreign demand shifter (b1)
            0.4910 ...          % 7. foreign demand curvature (b2)
            0.1139 ...          % *8. sd of omega1 (omega1_sd)
            0.1244, ...         % *9. sd of omega0 (omega0_sd)
            0.1189, ...         % 10.correlation (sigma_rho)
            -0.1066, ...        % 11.omega2
            ];   
    

%% Estimation: fminsearch    

    % initialize
    num_guess = 0;
    start_time = tic;    

    % adjustment
    adj_index = [1 2 5 8 9];
    adj_initial = init;
    for i = adj_index
        adj_initial(i) = log(adj_initial(i));
    end

    % options
    fmins_option = optimset('TolFun',1e-6, 'TolX',1e-6, 'MaxIter',5000, 'MaxFunEvals',1e4);             
        
    % fminsearch
    objfcn = @(est) est_obj(est, param, data, adj_index, start_time);    
    [est, fmins_fval, fmins_exitflag] = fminsearch(objfcn, adj_initial, fmins_option); 
    
    % adjustment (back)
    for i = adj_index
        est(i) = exp(est(i));
    end
    
    
 %% Save estimates
    
    % create folder
    mkdir('../../output/estimates') 

    % save
    save('../../output/estimates/fullmodel_estimates.mat', 'est');    
    
    
 
    